<?php

namespace app\admin\service\common;

use app\admin\model\admin\Dept as DeptModel;
use app\common\Constants;
use think\db\Query;
use think\facade\Log;

class DataScopeService
{
    private static $deptCache = [];

    public function apply(Query $query, array $userInfo, string $tableIdentifier): void
    {
        if (!$userInfo) {
            $query->whereRaw("1 = 0");
            return;
        }

        // 提取数据权限参数
        $type = $userInfo['scope'] ?? Constants::DATA_SCOPE_NONE;
        $deptId = $userInfo['deptId'] ?? 0;
        $customDeptIds = $userInfo['deptIds'] ?? [];
        $userId = $userInfo['id'] ?? 0;
        $create_detp_field = $tableIdentifier . '.' .Constants::TABLE_FIELD_CREATE_DEPT;
        $create_id_field =  $tableIdentifier . '.' .Constants::TABLE_FIELD_CREATE_ID;

        // 根据不同类型应用不同查询条件
        switch ($type) {
            case Constants::DATA_SCOPE_ALL:
                break;
            case Constants::DATA_SCOPE_DEPT_CUSTOM:
                if (!empty($customDeptIds)) {
                    $query->whereIn($create_detp_field, $customDeptIds);
                } else {
                    $query->whereRaw('1 = 0');
                }
                break;
            case Constants::DATA_SCOPE_DEPT_AND_SUB:
                $deptIds = $this->getDeptAndSubDeptIds($deptId);
                $query->whereIn($create_detp_field, $deptIds);
                break;
            case Constants::DATA_SCOPE_DEPT_CURRENT:
                $query->where($create_detp_field, $deptId);
                break;
            case Constants::DATA_SCOPE_SELF:
                $query->where($create_id_field, $userId);
                break;
            case Constants::DATA_SCOPE_NONE:
            default:
                $query->whereRaw("1 = 0");
                break;
        }
    }

    protected function getDeptAndSubDeptIds(int $deptId): array
    {
        // 检查缓存
        if (isset(self::$deptCache[$deptId])) {
            return self::$deptCache[$deptId];
        }

        // 获取所有子部门ID（递归）
        $childrenIds = [];
        $deptModel = new DeptModel();
        $depts = $deptModel->where('pid', $deptId)->select();

        // 递归终止条件：如果没有子部门
        if ($depts->isEmpty()) {
            self::$deptCache[$deptId] = [$deptId];
            return [$deptId];
        }

        foreach ($depts as $dept) {
            $subIds = $this->getDeptAndSubDeptIds($dept->id);
            $childrenIds = array_merge($childrenIds, $subIds);
        }

        $result = array_unique(array_merge([$deptId], $childrenIds));
        self::$deptCache[$deptId] = $result;

        return $result;
    }
}